package com.qx.chat.system.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * 
 * 上传文件
 * @ClassName: FileController
 * @version V1.0
 * @date 2015年12月25日
 * @author cyf
 */
@Controller
@Scope(value = "prototype")
@RequestMapping(value = "/file")
public class FileController {
	
	private String fileName;

	@RequestMapping("/uploadFile")
	public String uploadHeadPic(@RequestParam("file") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			upload(file, "/upload/user/", request);
			response.getWriter().print(getFileName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * 功能：文件上传
	 * @author cyf
	 * @date 2015年12月25日
	 * @param files
	 * @param destDir
	 * @throws Exception
	 */
	private void upload(MultipartFile file, String destDir, HttpServletRequest request) throws Exception {
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
		try {
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
			String realPath = request.getSession().getServletContext().getRealPath("/");
			File destFile = new File(realPath + destDir);
			if (!destFile.exists()) {
				destFile.mkdirs();
			}
			String fileNameNew = getFileNameNew() + "." + suffix;
			File f = new File(destFile.getAbsoluteFile() + "/" + fileNameNew);
			file.transferTo(f);
			f.createNewFile();
			fileName = basePath + destDir + fileNameNew;
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 
	 * 功能：重新命名文件
	 * 
	 * @author cyf
	 * @date 2015年12月25日
	 * @return
	 */
	private String getFileNameNew() {
		SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		return fmt.format(new Date());
	}
	
	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

}